package com.googlecode.worktools.ui;
import gr.zeus.ui.JConsole;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.googlecode.worktools.domain.FunctionInfo;
import com.googlecode.worktools.service.datatruncation.DBConn;
import com.googlecode.worktools.utils.FunctionUtils;
import com.googlecode.worktools.utils.UIUtils;
import com.googlecode.worktools.widgets.ButtonTabComponent;

/**
 * 工具箱主框架
 * @author Kobe Su,2009-11-30
 */
public class WorkToolsMainFrame extends javax.swing.JFrame {

	{
		//Set Look & Feel
		try {
			//UIManager.setLookAndFeel("napkin.NapkinLookAndFeel");
			//UIManager.setLookAndFeel("com.jgoodies.looks.plastic.Plastic3DLookAndFeel");		
			//UIManager.setLookAndFeel("org.jvnet.substance.skin.SubstanceTwilightLookAndFeel");
			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
			//UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private static final Log log = LogFactory.getLog(WorkToolsMainFrame.class);
	private JMenuItem helpMenuItem;
	private JMenu jMenu5;
	private JMenuItem logConsole;
	private JMenu toolMenu;
	private JScrollPane funDirScrollPane;
	private JScrollPane funwinScrollPane;
	private JTabbedPane jTabbedPane1;
	private JPanel rightBottomPanel;
	private JPanel rightTopPanel;
	private JLabel leftTopTitle;
	private JTree functionTree;
	private JPanel leftBottomPanel;
	private JPanel leftTopPanel;
	private JPanel leftPanel;
	private JPanel rightPanel;
	private JSplitPane jSplitPane1;
	private JMenuItem exitMenuItem;
	private JLabel rightTopLabel;
	private JMenu jMenu3;
	private JMenuBar jMenuBar1;
	private BaseFunctionPanel funPanel;
	private JConsole jconsole;
	private JPopupMenu popup;
	
	/**
	* Auto-generated main method to display this JFrame
	*/
	public static void main(String[] args) {
		JFrame.setDefaultLookAndFeelDecorated(true);
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				WorkToolsMainFrame inst = new WorkToolsMainFrame();
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}
	
	public WorkToolsMainFrame() {
		super();
		initGUI();
		initJConsole();
		//JConsole.getConsole().startConsole();
	}
	
	private void initGUI() {
		try {
			
			setDefaultCloseOperation(EXIT_ON_CLOSE);
			this.setIconImage(new ImageIcon(getClass().getResource("/rescources/images/run.gif")).getImage());
			this.setTitle("工作小工具箱");
			this.addWindowListener(new WindowAdapter() {
				
				@Override
				public void windowClosing(WindowEvent e) {
					DBConn.getInstance().closeConn();
					super.windowClosing(e);
				}
			});
			
			{
				jSplitPane1 = new JSplitPane();
				getContentPane().add(jSplitPane1, BorderLayout.CENTER);
				{
					leftPanel = new JPanel();
					BorderLayout leftPanelLayout = new BorderLayout();
					leftPanel.setLayout(leftPanelLayout);
					jSplitPane1.add(leftPanel, JSplitPane.LEFT);
					leftPanel.setPreferredSize(new java.awt.Dimension(135, 506));
					{
						leftTopPanel = new JPanel();
						leftPanel.add(leftTopPanel, BorderLayout.NORTH);
						leftTopPanel.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
						leftTopPanel.setBackground(new java.awt.Color(183,183,242));
						{
							leftTopTitle = new JLabel();
							leftTopPanel.add(leftTopTitle);
							leftTopTitle.setText("\u529f\u80fd\u5bfc\u822a");
						}
					}
					{
						leftBottomPanel = new JPanel();
						BorderLayout leftBottomPanelLayout = new BorderLayout();
						leftBottomPanel.setLayout(leftBottomPanelLayout);
						leftPanel.add(leftBottomPanel, BorderLayout.CENTER);
						{
							funDirScrollPane = new JScrollPane();
							leftBottomPanel.add(funDirScrollPane, BorderLayout.CENTER);
							{
								
								DefaultMutableTreeNode root = new DefaultMutableTreeNode("功能点");
								for(FunctionInfo function : FunctionUtils.getFunctionDatas())
									root.add(new DefaultMutableTreeNode(function));
								functionTree = new JTree(root);
								funDirScrollPane.setViewportView(functionTree);
								functionTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
								functionTree.addTreeSelectionListener(new TreeSelectionListener() {
									public void valueChanged(TreeSelectionEvent evt) {
										selectedTreeNode();
									}
								});
							}
						}
					}
				}
				{
					rightPanel = new JPanel();
					BorderLayout rightPanelLayout = new BorderLayout();
					rightPanel.setLayout(rightPanelLayout);
					jSplitPane1.add(rightPanel, JSplitPane.RIGHT);
					{
						rightTopPanel = new JPanel();
						rightPanel.add(rightTopPanel, BorderLayout.NORTH);
						rightTopPanel.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
						rightTopPanel.setBackground(new java.awt.Color(183,183,242));
						{
							rightTopLabel = new JLabel();
							rightTopPanel.add(rightTopLabel);
							rightTopLabel.setText("\u529f\u80fd\u4e3b\u7a97\u53e3");
						}
					}
					{
						rightBottomPanel = new JPanel();
						BorderLayout rightBottomPanelLayout = new BorderLayout();
						rightBottomPanel.setLayout(rightBottomPanelLayout);
						rightPanel.add(rightBottomPanel, BorderLayout.CENTER);
						{
							funwinScrollPane = new JScrollPane();
							rightBottomPanel.add(funwinScrollPane, BorderLayout.CENTER);
							{
								jTabbedPane1 = new JTabbedPane();
								funwinScrollPane.setViewportView(jTabbedPane1);
								jTabbedPane1.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
							}
						}
					}
				}
			}
			this.setSize(840, 610);
			{
				jMenuBar1 = new JMenuBar();
				setJMenuBar(jMenuBar1);
				{
					jMenu3 = new JMenu();
					jMenuBar1.add(jMenu3);
					jMenu3.setText("\u6587\u4ef6");
					{
						exitMenuItem = new JMenuItem();
						jMenu3.add(exitMenuItem);
						exitMenuItem.setText("\u9000\u51fa");
						exitMenuItem.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								DBConn.getInstance().closeConn();
								System.exit(0);
							}
						});
					}
				}
				{
					toolMenu = new JMenu();
					jMenuBar1.add(toolMenu);
					toolMenu.setText("\u5de5\u5177");
					{
						logConsole = new JMenuItem();
						toolMenu.add(logConsole);
						logConsole.setText("\u63a7\u5236\u53f0");
						logConsole.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								consoleActionPerformed(evt);
							}
						});
					}
				}
				{
					jMenu5 = new JMenu();
					jMenuBar1.add(jMenu5);
					jMenu5.setText("\u5e2e\u52a9");
					{
						helpMenuItem = new JMenuItem();
						jMenu5.add(helpMenuItem);
						helpMenuItem.setText("\u5173\u4e8e");
						helpMenuItem.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
			                    JOptionPane.showMessageDialog(WorkToolsMainFrame.this,"Version: 0.1\nAuthor: Kobe Su","About",JOptionPane.INFORMATION_MESSAGE);
							}
						});						
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//选中树节点时
	private void selectedTreeNode() {
		DefaultMutableTreeNode note = (DefaultMutableTreeNode)functionTree.getLastSelectedPathComponent();
		if(note == null)
			return;
		String className = null;
		if(note.isLeaf()) {
			FunctionInfo function = (FunctionInfo)note.getUserObject();
			String functionId = function.getFunctionId();
			String title = function.getFunctionName();
			className = function.getFunctionPanelClass();
			//log.debug(title);
			//System.out.println(title);
			try {
				funPanel = FunctionUtils.getFunctionPanel(functionId);
				if(funPanel == null) {
					funPanel = (BaseFunctionPanel)Class.forName(className).newInstance();
					FunctionUtils.addFunctionPanel(functionId, funPanel);	
					funPanel.setPanelId(functionId);
				}
				if(jTabbedPane1.indexOfComponent(funPanel) == -1) {
					jTabbedPane1.add(title, funPanel);				
					jTabbedPane1.addChangeListener(new ChangeListener() {
						@Override
						public void stateChanged(ChangeEvent e) {
							changeTab();
						}													
					});
				}
				jTabbedPane1.setSelectedComponent(funPanel);
				int selectedIndex = jTabbedPane1.getSelectedIndex();
				jTabbedPane1.setTabComponentAt(selectedIndex,new ButtonTabComponent(jTabbedPane1));
				
			} catch (InstantiationException e) {
				log.error(e.getMessage(),e);
			} catch (IllegalAccessException e) {
				log.error(e.getMessage(),e);
			} catch (ClassNotFoundException e) {
				log.error(e.getMessage(),e);
				UIUtils.showErrorMsg(this, "找不到类："+className);
			}
		}
	}	
	
	//tab页状态变化时
	private void changeTab() {
		BaseFunctionPanel panel = (BaseFunctionPanel)jTabbedPane1.getSelectedComponent();
		DefaultMutableTreeNode note = (DefaultMutableTreeNode)functionTree.getLastSelectedPathComponent();
		if(note == null)
			return;
		if(note.isLeaf()) {
			DefaultMutableTreeNode root = (DefaultMutableTreeNode)note.getParent();
			if(panel == null) {
				functionTree.setSelectionPath(new TreePath(root.getPath()));
				return;
			}
			int childNum = root.getChildCount();
			for(int i=0;i<childNum;i++) {
				DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)note.getParent().getChildAt(i);
				FunctionInfo function = (FunctionInfo)treeNode.getUserObject();
				String functionId = function.getFunctionId();
				if(panel.getPanelId().equals(functionId)) 
					functionTree.setSelectionPath(new TreePath(treeNode.getPath()));
			}			
		}
	}		
	
	private void initJConsole() {
		jconsole = new JConsole();
		jconsole.setTitle("控制台");
		jconsole.getConsole().setClearButtonText("清屏");
		jconsole.getConsole().setCloseButtonText("关闭");
		jconsole.getConsole().setSaveButtonText("保存");
		
		popup = new JPopupMenu(); 
		JCheckBoxMenuItem item1 = new JCheckBoxMenuItem("窗口置顶");
		item1.setSelected(true);
		item1.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if(e.getStateChange() == ItemEvent.SELECTED) 
					jconsole.setAlwaysOnTop(true);
				if(e.getStateChange() == ItemEvent.DESELECTED) 
					jconsole.setAlwaysOnTop(false);
			}	
		});
		popup.add(item1);		
		jconsole.getContentPane().addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent event) {
				if (event.isPopupTrigger())
					popup.show(event.getComponent(), event.getX(), event.getY());
			}
			public void mouseReleased(MouseEvent event) {
				if (event.isPopupTrigger())
					popup.show(event.getComponent(), event.getX(), event.getY());
			}
		});
	}
	
	private void consoleActionPerformed(ActionEvent evt) {
		jconsole.getConsole().startConsole();
		jconsole.setAlwaysOnTop(true);
		jconsole.setVisible(true);
	}

}
